/*
 * @Description: 最小订单金额规则详情页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2020-10-21 17:30:52
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-25 16:55:59
 */
import React, { useEffect, useState } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import { Button, DataSet, Form, notification, NumberField, Output, Select } from 'choerodon-ui/pro';
import { useDataSet, useDataSetEvent } from 'hzero-front/lib/utils/hooks';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import querystring from 'querystring';
import intl from 'utils/intl';
import {
  orderDistributionDtlFormDS,
  orderDistributionDtlTableDS,
  areaDateSet,
} from '../../stores/minOrderDtlDS';
import ProductTable from './component/productTable';
import AreaTree from './component/areaTree';
import { closeTab, openTab } from 'hzero-front/lib/utils/menuTab';
import formatterCollections from 'utils/intl/formatterCollections';

notification.config({
  duration: 3,
  placement: 'bottomRight',
});
interface propstype {
  dispatch: any;
  location: any;
}

const ClassPage: React.FC<propstype> = ({ dispatch, location }) => {
  const tableDS = useDataSet(() => new DataSet(orderDistributionDtlTableDS() as DataSetProps));
  const formDS = useDataSet(() => new DataSet(orderDistributionDtlFormDS() as DataSetProps));
  const areaDS = useDataSet(() => new DataSet(areaDateSet() as DataSetProps));

  const [showAgentLine, setShowAgentLine] = useState(false);

  const { search } = location;
  const queryStr: any = new URLSearchParams(search).get('params');
  const urlParamsObj = JSON.parse(decodeURIComponent(queryStr)) || {};

  useEffect(() => {
    if (urlParamsObj && urlParamsObj.id) {
      reqDetailData(urlParamsObj.id);
    }else{
      tableDS.loadData([])
      formDS.removeAll();
      formDS.create({}, 0);
      areaDS.removeAll()
    }
  }, [location.search]);

  useDataSetEvent(formDS, 'update', ({ dataSet, name }) => {
    if (name === 'amountRuleType') {
      const currentRecord = dataSet.current;
      if (currentRecord.get('amountRuleType') === 'agent') {
        setShowAgentLine(true);
        console.log(showAgentLine);
      }
    }
  });

  //请求详情id
  const reqDetailData = id => {
    const numberId = Number(id);
    // 请求头
    formDS.setQueryParameter('ruleId', numberId);
    formDS.query();
    // 请求行
    tableDS.setQueryParameter('ruleId', numberId);
    tableDS.query();
  };

  // 封装，区域列表上传数据
  const submitAreaData = () => {
    let djiomOrderAmountRuleAreas: any = [];
    const treeList = areaDS.toData();
    if (treeList) {
      djiomOrderAmountRuleAreas = treeList.filter((item: any) => {
        item.regionId = formDS.current?.get('regionId');
        item.areaId = item.parentCodeValue;
        item.countryId = item.value;
        return item.parentCodeValue && item.check;
      });
    }
    return djiomOrderAmountRuleAreas;
  };

  const handleSave = async () => {
    const areaData = submitAreaData();
    const lineData = tableDS.toData();
    if (!areaData.length) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get('dji.otc.om.view.field.regionaCountryRequire').d('区域国家未勾选！！'),
      });
      return;
    }
    if (!lineData.length) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get('dji.otc.om.view.field.ruleLineRequire').d('校验规则行未填写！！'),
      });
      return;
    }
    const validate = await tableDS.validate();
    if(!validate){
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get('dji.otc.om.view.field.ruleLineDetailRequire').d('校验规则行明细未填写！！'),
      });
      return;
    }

    formDS.current?.set('djiomOrderAmountRuleAreas', areaData);
    formDS.current?.set('djiomOrderAmountRuleDetails', lineData);

    formDS.submit().then(res => {
      // 新增
      const id = res.content && res.content[0].ruleId;
      dispatch(
        routerRedux.push({
          pathname: `/o2om/min-order-amount-rule/create`,
          search: querystring.stringify({
            params: encodeURIComponent(JSON.stringify({ id, number: Math.random() })),
          }),
        })
      );
      // reqDetailData(id);
    });
  };

  const handleCancel = () => {
    const closeUrl = '/o2om/min-order-amount-rule/create';
    const openUrl = '/o2om/min-order-amount-rule';
    handleTabs(closeUrl, openUrl);
  };

  // 关闭当前tab,打开指定tab
  const handleTabs = (closeUrl, openUrl?) => {
    openTab({
      key: openUrl, // 回到list页面
    });
    if (openUrl) {
      closeTab(closeUrl);
    }
  };

  return (
    <PageHeaderWrapper
      title={
        urlParamsObj
          ? intl.get('dji.otc.om.view.title.editMinRule').d('编辑订单金额校验规则')
          : intl.get('dji.otc.om.view.title.createMinRule').d('新建订单金额校验规则')
      }
      header={
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button key="cancel" onClick={() => handleCancel()}>
            {intl.get(`dji.otc.om.view.field.cancel`).d('取消')}
          </Button>
          <Button icon="save" key="save" onClick={() => handleSave()}>
            {intl.get(`dji.otc.om.view.button.save`).d('保存')}
          </Button>
        </div>
      }
    >
      <Form dataSet={formDS} columns={2}>
        <Select name="businessGroup" />
        <Select name="amountRuleType" />
        <NumberField name="priority" />
        <Select name="regionId" />
        <Output name="areaControyLabel" required />
      </Form>
      <AreaTree
        areaDS={areaDS}
        tableDS={tableDS}
        treeStyle={{ marginLeft: 100, marginTop: -36 }}
        parentDS={formDS}
        ruleId={urlParamsObj ? urlParamsObj.id : ''}
        disabledFlag={false}
      />
      <ProductTable tableDS={tableDS} dispatch={dispatch} parentDS={formDS} areaDS={areaDS}/>
    </PageHeaderWrapper>
  );
};

export default connect()(
  formatterCollections({
    code: 'dji.otc.om',
  })(ClassPage)
);
